import React, {Component, Fragment} from 'react';
import {Button, Card, message, Tabs, List, Modal, Spin} from 'antd';
import {PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined} from "@ant-design/icons";
import {reqBookCategory, reqDeleteBookCategory, reqAddBookCategory, reqUpdateBookCategory} from '../../api/book';
import {CategoryAddForm, UpdateForm} from '../../components/Book/category/Form/index';

const {TabPane} = Tabs;

export default class BookCategory extends Component {
  state = {
    result: [], // 结果
    isModalVisible: false, // 显隐modal
    updateVisible: false,
    value: {}, // 标签的值
    tabs: [], // tab栏的值
    formRef: {}, // 表单实例
    loading: true, // 加载动画
  }

  // 显示modal
  showModal = (c, value = {}) => {
    if (c === 'add') {
      this.setState({isModalVisible: true});
    } else if (c === 'update') {
      this.setState({updateVisible: true, value});
    } else { // 删除
      Modal.confirm({
        title: '删除标签',
        icon: <ExclamationCircleOutlined/>,
        content: '请注意，你将永久删除该标签！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => this.handleOk('delete', value)
      });
    }
  }
  // 获取全部图书类型
  getBookCategories = async () => {
    try {
      const {data: result} = await reqBookCategory();
      const tabs = result.map(i => i.name)
      this.setState({loading: false});
      this.setState({result, tabs})
    } catch (e) {
      console.log(e);
      message.error(e.message);
      this.setState({loading: false});
    }
  }
  // 删除图书类别
  deleteBookCategory = async (val) => {
    try {
      const res = await reqDeleteBookCategory(val.id);
      if (res.status === 204) {
        message.success('删除标签成功');
        const {result} = this.state;
        const item = result.find(item => item.name === val.category);
        const i = item.children.find(a => a.name === val.tag);
        item.children.splice(item.children.indexOf(i), 1);
        this.setState({result});
      } else {
        message.error(res.data.message);
      }
    } catch (e) {
      console.log(e)
      message.error(e.data.message);
    }
  }
  // 添加一条标签
  addBookCategory = async (data) => {
    try {
      const {data: res} = await reqAddBookCategory(data);
      if (res.status === 202) {
        message.error(res.message);
      } else {
        const {result} = this.state;
        const item = result.find(item => item.name === res.category);
        item.children.unshift({id: res._id, name: res.tag});
        this.setState({result, isModalVisible: false});
        message.success('添加标签成功');
      }
    } catch (e) {
      console.log(e);
      message.error(e.data.message);
    }
  }
  // 更新图书标签
  updateBookCategory = async (data) => {
    try {
      const {value} = this.state;
      const {data: res} = await reqUpdateBookCategory(value.id, data);
      const {result} = this.state;
      const item = result.find(item => item.name === res.category);
      const i = item.children.find(i => i.name === value.name);
      item.children.splice(item.children.indexOf(i), 1, Object.assign(i, {name: res.tag})); // 替换标签
      message.success('更新图书成功');
      this.setState({result, updateVisible: false});
    } catch (e) {
      console.log(e);
    }
  }

  componentDidMount() {
    this.getBookCategories();
  }

  getFormVal = (ref) => {
    this.setState({formRef: ref})
  }
  // 点击modal的保存
  handleOk = (c, value) => {
    if (c === 'add' || c === 'update') {
      const {formRef} = this.state;
      // 表单传递过来的值
      formRef.current.validateFields().then(values => {
        if (c === 'add') {
          this.addBookCategory(values)
        } else {
          this.updateBookCategory(values)
        }
      }).catch(err => {
        console.log(err);
      })
    } else {
      this.deleteBookCategory(value);
    }
  }

  // 点击modal的取消
  handleCancel = (c) => {
    if (c === 'add') {
      this.setState({isModalVisible: false});
    } else if (c === 'update') {
      this.setState({updateVisible: false});
    } else {
      this.setState({delVisible: false});
    }
  }

  render() {
    const {result, isModalVisible, updateVisible, value, tabs, loading} = this.state;
    const extra = (
      <Fragment>
        <Button type='primary' onClick={() => this.showModal('add')} icon={<PlusOutlined/>}
                style={{marginRight: '10px'}}>添加</Button>
      </Fragment>
    )
    return (
      <Card title='图书类别' bordered={false} extra={extra}>
        <div style={{textAlign: 'center'}}>
          <Spin tip="Loading..." spinning={loading}/>
        </div>
        <Tabs defaultActiveKey={result.length > 0 && result[0].id}>
          {
            result.map(i => {
              return (
                <TabPane tab={i.name} key={i.id}>
                  {
                    <List
                      dataSource={i.children}
                      renderItem={(item) => (
                        <List.Item
                          actions={[
                            <Button onClick={() => this.showModal('update', item)} type="primary"
                                    icon={<EditOutlined/>}>修改</Button>,
                            <Button danger onClick={() => this.showModal('delete',
                              {category: i.name, id: item.id, tag: item.name})} icon={<DeleteOutlined/>}>删除</Button>
                          ]}
                        >
                          {item.name}
                        </List.Item>
                      )}
                    />
                  }
                </TabPane>
              )
            })
          }
        </Tabs>
        <Modal title="添加标签"
               visible={isModalVisible}
               onOk={() => this.handleOk('add')}
               destroyOnClose
               onCancel={() => this.handleCancel('add')}>
          <CategoryAddForm tabs={tabs} getFormVal={(v) => this.getFormVal(v)}/>
        </Modal>
        <Modal title="更新标签"
               visible={updateVisible}
               onOk={() => this.handleOk('update')}
               destroyOnClose
               onCancel={() => this.handleCancel('update')}>
          <UpdateForm value={value} getFormVal={(v) => this.getFormVal(v)}/>
        </Modal>
      </Card>
    )
  }
}
